<template>
  <div class="batch-table">
    <table>
      <thead>
        <tr>
          <th>批次名称</th>
          <th>品牌</th>
          <th>季次</th>
          <th>状态</th>
          <th>统计信息</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr
          v-for="batch in batches"
          :key="batch.id"
          :class="{ 'flash-conflict': isFlashing(batch) }"
        >
          <td>
            <div class="batch-name-cell">
              <div class="batch-logo">
                <img :src="getBrandLogo(batch.brand)" :alt="batch.brand" class="brand-logo-img" />
              </div>
              <div class="batch-info">
                <div class="batch-name">{{ batch.name }}</div>
                <div class="batch-time">
                  {{ batch.importTime || '导入时间：--' }}
                </div>
              </div>
            </div>
          </td>
          <td>{{ batch.brand }}</td>
          <td>{{ batch.season }}</td>
          <td>
            <div class="status-cell">
              <span class="status-badge" :class="getStatusClass(batch.status)">
                {{ getStatusText(batch.status) }}
              </span>
              <div v-if="showImportProgress(batch)" class="import-progress">
                <div class="progress-bar">
                  <div
                    class="progress-fill"
                    :class="{ stopped: batch.importStatus === 'stopped' }"
                    :style="{ width: batch.importProgress + '%' }"
                  ></div>
                </div>
                <span class="progress-text">{{ batch.importProgress }}%</span>
              </div>
            </div>
          </td>
          <td>
            <div class="stats-cell">
              <div class="stats-row">
                <span class="stat-item">
                  <span class="stat-label">信息：</span>
                  <span class="stat-count">{{ batch.totalInfo || 0 }}</span>
                </span>
                <span class="stat-item">
                  <span class="stat-label">图片：</span>
                  <span class="stat-count">{{ batch.totalImages || 0 }}</span>
                </span>
              </div>
              <div class="stats-row">
                <span class="stat-item">
                  <span class="stat-label">款式：</span>
                  <span class="stat-count">{{ batch.identifiedStyles || 0 }}</span>
                </span>
                <span class="stat-item">
                  <span class="stat-label">颜色：</span>
                  <span class="stat-count">{{ batch.identifiedColors || 0 }}</span>
                </span>
              </div>
              <div v-if="hasAnomalies(batch)" class="anomalies-row">
                <span class="anomaly-item">
                  <span class="anomaly-label">异常：</span>
                  <span class="anomaly-count">{{ getTotalAnomalies(batch) }}</span>
                </span>
              </div>
            </div>
          </td>
          <td>
            <div class="table-actions">
              <button
                class="btn btn-sm"
                :class="getEnterMatchingButtonClass(batch)"
                @click="$emit('enter-matching', batch.id)"
                :disabled="isImporting(batch) || !canEnterMatching(batch)"
              >
                <EnterMatchingIcon :size="12" />
                进入匹配
              </button>
              <button
                class="btn btn-sm"
                @click="$emit('edit', batch)"
                :disabled="isImporting(batch)"
              >
                <EditIcon :size="12" />
                编辑
              </button>
              <button
                class="btn btn-sm"
                :class="getImportButtonClass(batch)"
                @click="$emit('import', batch.id)"
                :disabled="isImporting(batch) || !canImport(batch)"
              >
                <ImportIcon :size="12" />
                导入
              </button>
              <button
                class="btn btn-sm"
                :class="getUpdateVectorsButtonClass(batch)"
                @click="handleUpdateVectors(batch)"
                :disabled="
                  isImporting(batch) || !canUpdateVectors(batch) || isUpdateVectorsProcessing(batch)
                "
              >
                <UpdateVectorsIcon :size="12" />
                更新向量库
              </button>
              <button
                class="btn btn-sm"
                :class="getArchiveButtonClass(batch)"
                @click="handleArchive(batch)"
                :disabled="isImporting(batch) || !canArchive(batch) || isArchiveProcessing(batch)"
              >
                <ArchiveIcon :size="12" />
                {{ getArchiveButtonText(batch) }}
              </button>
              <button
                class="btn btn-sm btn-danger"
                @click="$emit('delete', batch)"
                :disabled="isImporting(batch)"
              >
                <DeleteIcon :size="12" />
                删除
              </button>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { generateLogoPlaceholder } from '../utils/logoPlaceholder'
import { createBatchButtonManager, getButtonClass } from '../utils/buttonStateManager'
import {
  EditIcon,
  DeleteIcon,
  ImportIcon,
  UpdateVectorsIcon,
  ArchiveIcon,
  EnterMatchingIcon,
} from './icons'

export default {
  name: 'BatchTable',
  components: {
    EditIcon,
    DeleteIcon,
    ImportIcon,
    UpdateVectorsIcon,
    ArchiveIcon,
    EnterMatchingIcon,
  },
  props: {
    batches: {
      type: Array,
      default: () => [],
    },
    brands: {
      type: Array,
      default: () => [],
    },
    flashingBatchId: {
      type: String,
      default: '',
    },
  },
  emits: ['enter-matching', 'edit', 'import', 'update-vectors', 'archive', 'delete'],
  setup(props, { emit }) {
    const buttonManagers = ref(new Map())

    // 初始化按钮管理器
    onMounted(() => {
      props.batches.forEach(batch => {
        if (!buttonManagers.value.has(batch.id)) {
          buttonManagers.value.set(batch.id, createBatchButtonManager(batch.id))
        }
      })
    })

    // 清理资源
    onUnmounted(() => {
      buttonManagers.value.forEach(manager => manager.clear())
      buttonManagers.value.clear()
    })

    // 获取按钮管理器
    const getButtonManager = batchId => {
      if (!buttonManagers.value.has(batchId)) {
        buttonManagers.value.set(batchId, createBatchButtonManager(batchId))
      }
      return buttonManagers.value.get(batchId)
    }

    // 按钮处理状态
    const isUpdateVectorsProcessing = batch => {
      const manager = getButtonManager(batch.id)
      return manager?.isProcessing(`update-vectors_${batch.id}`) || false
    }

    const isArchiveProcessing = batch => {
      const manager = getButtonManager(batch.id)
      return manager?.isProcessing(`archive_${batch.id}`) || false
    }

    // 获取品牌Logo
    const getBrandLogo = brand => {
      if (!brand) return generateLogoPlaceholder('Unknown')
      const brandData = props.brands.find(b => b.name === brand)
      return brandData?.logo || generateLogoPlaceholder(brand)
    }

    // 判断是否有异常
    const hasAnomalies = batch => {
      const anomalies = batch.anomalies || {}
      return Object.values(anomalies).some(count => count > 0)
    }

    // 获取异常总数
    const getTotalAnomalies = batch => {
      const anomalies = batch.anomalies || {}
      return Object.values(anomalies).reduce((sum, count) => sum + (count || 0), 0)
    }

    // 显示导入进度
    const showImportProgress = batch => {
      return (
        batch.importStatus === 'importing' ||
        (batch.importStatus === 'stopped' && batch.importProgress > 0)
      )
    }

    // 判断是否正在导入
    const isImporting = batch => {
      return batch.status === 'importing' && batch.importStatus === 'importing'
    }

    // 判断是否正在闪烁
    const isFlashing = batch => {
      return String(props.flashingBatchId) === String(batch.id)
    }

    // 按钮状态计算
    const canEnterMatching = batch => {
      return ['import_completed', 'matching_completed', 'vector_completed', 'archived'].includes(
        batch.status
      )
    }

    const canImport = batch => {
      // 导入按钮在所有非导入中状态下都应该可用
      return batch.importStatus !== 'importing'
    }

    const canUpdateVectors = batch => {
      return ['matching_completed'].includes(batch.status)
    }

    const canArchive = batch => {
      return ['import_completed', 'vector_completed', 'archived'].includes(batch.status)
    }

    // 按钮样式方法
    const getEnterMatchingButtonClass = batch => {
      if (['import_completed'].includes(batch.status)) {
        return 'btn-primary'
      }
      return ''
    }

    const getUpdateVectorsButtonClass = batch => {
      const baseClass = batch.status === 'matching_completed' ? 'btn-primary' : ''
      return getButtonClass(
        `update-vectors_${batch.id}`,
        isUpdateVectorsProcessing(batch),
        baseClass
      )
    }

    const getImportButtonClass = batch => {
      if (['new', 'import_stopped'].includes(batch.status)) {
        return 'btn-primary'
      }
      return ''
    }

    const getArchiveButtonClass = batch => {
      const baseClass = ['import_completed', 'vector_completed', 'archived'].includes(batch.status)
        ? 'btn-primary'
        : ''
      return getButtonClass(`archive_${batch.id}`, isArchiveProcessing(batch), baseClass)
    }

    // 获取归档按钮文本
    const getArchiveButtonText = batch => {
      return batch.status === 'archived' ? '恢复' : '归档'
    }

    // 按钮处理函数
    const handleUpdateVectors = batch => {
      const manager = getButtonManager(batch.id)
      if (!manager) return

      manager.debounce(`update-vectors_${batch.id}`, async () => {
        try {
          manager.setProcessing(`update-vectors_${batch.id}`, true)

          // 直接调用API
          const { updateBatchVectors } = await import('../api/batchApi')
          const res = await updateBatchVectors(batch.id)
          console.log('更新向量库结果:', res)

          if (res.code === 200) {
            // 使用Element Plus的消息提示
            const { ElMessage } = await import('element-plus')
            ElMessage.success(res.message || '更新向量库成功')
            // 发出事件通知父组件刷新数据
            emit('update-vectors', batch.id)
          } else {
            const { ElMessage } = await import('element-plus')
            ElMessage.error(res.message || '更新向量库失败')
          }
        } catch (error) {
          console.error('更新向量库失败:', error)
          const { ElMessage } = await import('element-plus')
          ElMessage.error('更新向量库失败')
        } finally {
          manager.setProcessing(`update-vectors_${batch.id}`, false)
        }
      })
    }

    const handleArchive = batch => {
      const manager = getButtonManager(batch.id)
      if (!manager) return

      manager.debounce(`archive_${batch.id}`, async () => {
        try {
          manager.setProcessing(`archive_${batch.id}`, true)

          // 根据批次状态决定调用归档还是取消归档API
          const { archiveBatch, unarchiveBatch } = await import('../api/batchApi')
          let res

          if (batch.status === 'archived') {
            // 如果批次已归档，则调用取消归档API
            res = await unarchiveBatch(batch.id)
          } else {
            // 否则调用归档API
            res = await archiveBatch(batch.id)
          }

          console.log('归档操作结果:', res)

          if (res.code === 200) {
            const { ElMessage } = await import('element-plus')
            ElMessage.success(res.message || '归档操作成功')
            // 发出事件通知父组件刷新数据
            emit('archive', batch.id)
          } else {
            const { ElMessage } = await import('element-plus')
            ElMessage.error(res.message || '归档操作失败')
          }
        } catch (error) {
          console.error('归档操作失败:', error)
          const { ElMessage } = await import('element-plus')
          ElMessage.error('归档操作失败')
        } finally {
          manager.setProcessing(`archive_${batch.id}`, false)
        }
      })
    }

    // 状态相关方法
    const getStatusText = status => {
      const statusMap = {
        new: '新建',
        importing: '导入中',
        import_completed: '导入完成',
        matching_completed: '匹配完成',
        vector_completed: '向量完成',
        archived: '已归档',
        import_stopped: '导入停止',
      }
      return statusMap[status] || status
    }

    const getStatusClass = status => {
      const classMap = {
        new: 'status-new',
        importing: 'status-importing',
        import_completed: 'status-import-completed',
        matching_completed: 'status-matching-completed',
        vector_completed: 'status-vector-completed',
        archived: 'status-archived',
        import_stopped: 'status-import-stopped',
      }
      return classMap[status] || 'status-default'
    }

    return {
      getBrandLogo,
      hasAnomalies,
      showImportProgress,
      isFlashing,
      isImporting,
      canEnterMatching,
      canImport,
      canUpdateVectors,
      canArchive,
      getEnterMatchingButtonClass,
      getImportButtonClass,
      getUpdateVectorsButtonClass,
      getArchiveButtonClass,
      getArchiveButtonText,
      getStatusText,
      getStatusClass,
      getTotalAnomalies,
      // 按钮处理状态
      isUpdateVectorsProcessing,
      isArchiveProcessing,
      // 按钮处理函数
      handleUpdateVectors,
      handleArchive,
    }
  },
}
</script>

<style scoped>
/* 引入按钮动画样式 */
@import '../styles/button-animations.css';

.batch-table {
  width: 100%;
  overflow-x: auto;
}

.batch-table table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  border-radius: var(--border-radius);
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.batch-table th,
.batch-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

.batch-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: var(--text-color);
  font-size: 14px;
}

.batch-table td {
  font-size: 14px;
  color: var(--text-color);
}

.batch-name-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.batch-logo {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.brand-logo-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.batch-info {
  flex: 1;
  min-width: 0;
}

.batch-name {
  font-weight: 600;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.batch-time {
  font-size: 12px;
  color: var(--text-secondary);
}

.status-cell {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.status-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
  white-space: nowrap;
}

.status-new {
  background: #e6f7ff;
  color: #1890ff;
}

.status-importing {
  background: #fff7e6;
  color: #fa8c16;
}

.status-import-completed {
  background: #f6ffed;
  color: #52c41a;
}

.status-matching-completed {
  background: #f0f5ff;
  color: #1890ff;
}

.status-vector-completed {
  background: #f9f0ff;
  color: #722ed1;
}

.status-archived {
  background: #f5f5f5;
  color: #666;
}

.status-import-stopped {
  background: #fff2f0;
  color: #ff4d4f;
}

.status-default {
  background: #f5f5f5;
  color: #666;
}

.import-progress {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-bar {
  flex: 1;
  height: 6px;
  background: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #1890ff;
  transition: width 0.3s ease;
}

.progress-fill.stopped {
  background: #ff4d4f;
}

.progress-text {
  font-size: 12px;
  color: var(--text-secondary);
  min-width: 30px;
}

.stats-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stats-row {
  display: flex;
  gap: 12px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-label {
  font-size: 12px;
  color: var(--text-secondary);
}

.stat-count {
  font-weight: 600;
  color: var(--text-color);
}

.anomalies-row {
  margin-top: 4px;
}

.anomaly-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.anomaly-label {
  font-size: 12px;
  color: var(--text-secondary);
}

.anomaly-count {
  font-weight: 600;
  color: #fa8c16;
}

.table-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.table-actions .btn {
  padding: 4px 8px;
  font-size: 12px;
  white-space: nowrap;
}

/* 闪烁动画 */
.flash-conflict {
  animation: flash-conflict 0.8s ease-in-out 3;
}

@keyframes flash-conflict {
  0%,
  100% {
    background: white;
  }
  50% {
    background: #fff2f0;
  }
}

@media (max-width: 768px) {
  .batch-table {
    font-size: 12px;
  }

  .batch-table th,
  .batch-table td {
    padding: 8px 6px;
  }

  .table-actions {
    flex-direction: column;
    gap: 4px;
  }

  .table-actions .btn {
    width: 100%;
    justify-content: center;
  }
}
</style>
